package org.swfer.UICExtend 
{
	import flash.events.TimerEvent;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	
	/**
	 * 时间节点管理器
	 * @author swfer
	 */
	public class TimerManager implements ITimerManager
	{
		/** 最小定时器间隔 **/
		public var timerStepInterval:uint = 33;
		
		private var timeNodeArr:Array;
		private var timer:Timer;
		private var orginTime:int;
		
		public function TimerManager() 
		{
			TimeNode.timerManager = this;
			timeNodeArr = [];
		}
		
		/**
		 * 加入节点时间队列
		 * @param	node
		 */
		public function pushNode(node:ITimeNode):void
		{
			if (!node) return;
			
			if (!timer) 
			{
				timer = new Timer(timerStepInterval);
				timer.addEventListener(TimerEvent.TIMER,onTimeStep);
			}
			if (timer.running == false)
			{
				timer.start();
				orginTime = getTimer();
			}
			
			node.startTime = getTimer();
			timeNodeArr.push(node);
		}
		
		/**
		 * 从时间队列移除节点
		 * @param	node
		 */
		public function removeNode(node:ITimeNode):void
		{
			var index:int = timeNodeArr.indexOf(node);
			if (index == -1) return;
			
			timeNodeArr.splice(index, 1);
		}
		
		/**
		 * 定时周期 更新队列
		 * @param	e
		 */
		private function onTimeStep(e:TimerEvent):void 
		{
			var currentTime:int = getTimer();
			var runtime:int = currentTime-orginTime;
			
			for each (var item:ITimeNode in timeNodeArr) 
			{
				if (item.death) removeNode(item);
				if (item.pause) continue;
				
				var dt:int = runtime-item.delay;
				
				if (dt<=0) continue;
				if (dt < (item.currentCount + 1) * item.interval) continue;
				
				item.currentCount += 1;
				if (item.currentCount >= item.repeatCount)
				{
					removeNode(item);
				}
			}
			
			if (timeNodeArr.length == 0)
			{
				timer.stop();
				return;
			}
		}
		
	}

}